//
//  YDPublishViewController.swift
//  weibo
//
//  Created by 孙亚东 on 16/6/30.
//  Copyright © 2016年 Sunyadong. All rights reserved.
//

import UIKit
//import IQKeyboardManager

class YDPublishViewController: UIViewController {
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        textV.becomeFirstResponder()
        
    }
    
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        
        NSNotificationCenter.defaultCenter().removeObserver(textV)
        
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.whiteColor()
        
    
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchKeyboard:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        setupNav()
        
        setupUI()

        
    }

    func switchKeyboard (noti: NSNotification){
        
        //改变toolBar的frame
        
        //判断当前键盘的位置
        
        let str = noti.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        if str?.origin.y == screenHeight {

            toolBar.snp_updateConstraints(closure: { (make) -> Void in
            
                make.bottom.equalTo(self.view.snp_bottom).offset(0)
                
            })

  
            
        }else {
            
            
            toolBar.snp_updateConstraints(closure: { (make) -> Void in
                
                make.bottom.equalTo(self.view.snp_bottom).offset(-str.size.height)
                
                
            })

        }
        
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.toolBar.layoutIfNeeded()
            
        }

    }

    private func setupNav() {
    
        let leftButtn = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "backBtnClick")
        
        let rightButton = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "publishBtnClick")
        
        navigationItem.leftBarButtonItem = leftButtn
        
        navigationItem.rightBarButtonItem = rightButton
        
        // 设置title
        //创建一个lab
        let titleLab = YDTitleLab()
    
        navigationItem.titleView = titleLab

    }
    //实现方法
    
    func backBtnClick () {
    
        //让textView结束第一响应者
        
         textV.resignFirstResponder()
    
        self.dismissViewControllerAnimated(true, completion: nil)

        
    }
    
    
    func publishBtnClick() {
        
        
//mark --- 发布功能实现

    }
    
    
    func setupUI(){
    
    //1. 添加textView
        self.view.addSubview(textV)

    //设置约束
        textV.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(self.view.snp_edges)
            
        }
    
        textV.delegate = self
        // textView和键盘相关的 keyboard
        textV.keyboardDismissMode = .OnDrag
        // 一定要设置alwaysBounceVertical 是垂直
        textV.alwaysBounceVertical = true
        
        //2. 添加choosePictureView
        
        self.view.addSubview(pictureView)
        
        //给闭包赋值
        
        
        pictureView.closure = { [weak self] ()->() in
            

             self?.choosePicture()
        
        
        }
    
        //设置约束
        pictureView.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(self.view.snp_left).offset(10)
            make.top.equalTo(self.view.snp_top).offset(200)
            
            make.width.height.equalTo(screenWidth - 20)
            
        }
        
   
        //3. 添加toolbar
        self.view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            
            make.left.right.bottom.equalTo(self.view)
            
            make.height.equalTo(44)
            
        }
    
 
    }
    
    //懒加载控件，添加textView
    private lazy var textV: YDTextView = {
    
        var textV = YDTextView()
        
        return textV

    
    
    }()
    
    
    private lazy var toolBar: UIToolbar = {
    
        var bar = UIToolbar()
        
        bar.backgroundColor = UIColor.lightGrayColor()
        // 我们可以把一些固定的东西按照数据源的形式,展示
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        
        // 初始化一个数组
        var items = [UIBarButtonItem]()
        
        //遍历数组
        for itemSetting in itemSettings {
            
         //创建item
            let imageNa = itemSetting["imageName"]
            
            var act: String
            
            let actSelect: Selector
            
            if itemSetting.count > 1 {
            
            
                 act = itemSetting["action"]!
                
                 actSelect = Selector(act)
            
            }else{
            
                 actSelect = nil
            
            
            }
     
            let button: UIButton = UIButton(type: UIButtonType.Custom)
            
            button.setImage(UIImage(named:  imageNa!), forState: UIControlState.Normal)
            button.setImage(UIImage(named: "\(imageNa!)_highlighted"), forState: .Highlighted)
            
            button.addTarget(self, action: actSelect, forControlEvents: .TouchUpInside)
            
            button.sizeToFit()
            
            
            let item: UIBarButtonItem = UIBarButtonItem(customView: button)
            

            items.append(item)
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
         
        
        }
    
        items.removeLast()
        
        bar.items = items
        
    
        return bar
    }()
    
    
    private lazy var pictureView: YDChoosePictureView = {
        
        
        let chooseView = YDChoosePictureView()
 
        return chooseView
        
    
    }()
    
    lazy var  emoticonView : YDEmoticonView = {
    
        let emoticon = YDEmoticonView()
        
        return emoticon

    }()
    
    

}

//实现toolBar的按钮点击方法

extension YDPublishViewController {

    @objc private func choosePicture () {
        
        if self.pictureView.isPresent(){
        
            return
        
        }
 
        print("choosePicture")
        
        //获取图片
        let pick = UIImagePickerController()
        
        pick.sourceType = .PhotoLibrary
        
        
        pick.delegate = self
        
        self .presentViewController(pick, animated: true, completion: nil)
        

    }
    
// MARK: 表情键盘
    @objc private func inputEmoticon () {


        self.textV.inputView = self.textV.inputView == nil ? emoticonView : nil

        self.textV.reloadInputViews()
        
        self.textV.becomeFirstResponder()
        

    }

}


//实现imagePickView的代理方法

extension YDPublishViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
 
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
    
        self.pictureView.addImage(image)
 
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }
    

}

//实现代理方法
extension YDPublishViewController: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        
        textV.textLab.text = ""
        
        if textV.text.characters.count == 0 {
        
        textV.textLab.text = "你大爷"
        
        
        }
    
    }

}
 